//
//  EVEmptyView.m
//  EVClub
//
//  Created by LiJieming on 15/6/2.
//  Copyright (c) 2015年 BitRice. All rights reserved.
//

#import "EVEmptyView.h"

#import "UIView+EV.h"
#import "UIColor+EV.h"
#import "NSError+EV.h"
#import "NSDictionary+EV.h"
#import "UIView+EVCornerRadius.h"

#import "ReachabilityHelper.h"
#import <objc/runtime.h>

NSString *const EVEmptyViewDefault       = @"EmptyViewDefault";
NSString *const EVEmptyViewCustom        = @"EmptyViewCustom";
NSString *const EVEmptyViewError         = @"EmptyViewError";
NSString *const EVEmptyViewNetwork       = @"EmptyViewNetwork";
NSString *const EVEmptyViewSystemMessage = @"EmptyViewSystemMessage";
NSString *const EVEmptyViewOrder         = @"EmptyViewOrder";
NSString *const EVEmptyViewCoupon        = @"EmptyViewCoupon";

NSString *const EVEmptyViewLayoutKeyIcon        = @"icon";
NSString *const EVEmptyViewLayoutKeyMainTitle   = @"mainTitle";
NSString *const EVEmptyViewLayoutKeySecondTitle = @"secondTitle";
NSString *const EVEmptyViewLayoutKeyButtonTitle = @"buttonTitle";

@interface EVEmptyView ()

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *mainTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondTitleLabel;
@property (weak, nonatomic) IBOutlet UIButton *actionButton;

@end

@implementation EVEmptyView

- (UINib *)viewInitNib {
    return [UINib nibWithNibName:@"EVEmptyView" bundle:nil];
}

+ (instancetype)emptyViewWithType:(NSString *)emptyViewType actionBlock:(void(^)(void))actionBlock {
    EVEmptyView *emptyView  = [[EVEmptyView alloc] init];
    emptyView.emptyViewType = emptyViewType;
    emptyView.actionBlock   = actionBlock;
    
    return emptyView;
}

+ (instancetype)emptyViewWithIconImage:(UIImage *)iconImage mainTitle:(NSString *)mainTitle secondTitle:(NSString *)secondTitle actionButtonTitle:(NSString *)actionButtonTitle actionBlock:(void(^)(void))actionBlock; {
    EVEmptyView *emptyView = [[EVEmptyView alloc] init];;
    
    emptyView->_emptyViewType   = EVEmptyViewCustom;
    emptyView.iconImage         = iconImage;
    emptyView.mainTitle         = mainTitle;
    emptyView.secondTitle       = secondTitle;
    emptyView.actionButtonTitle = actionButtonTitle;
    emptyView.actionBlock       = actionBlock;
    
    return emptyView;
}

- (void)setEmptyViewType:(NSString *)emptyViewType {
    _emptyViewType = emptyViewType;
    
    if (![emptyViewType isEqualToString:EVEmptyViewCustom]) {
        NSAssert([[EVEmptyView emptyViewLayouts].allKeys containsObject:emptyViewType], @"Unexpert emptyView type: %@", emptyViewType);
        
        NSDictionary *layout   = [EVEmptyView emptyViewLayouts][emptyViewType];
        self.iconImage         = [layout ev_nilObjectForKey:EVEmptyViewLayoutKeyIcon];
        self.mainTitle         = [layout ev_stringObjectForKey:EVEmptyViewLayoutKeyMainTitle];
        self.secondTitle       = [layout ev_stringObjectForKey:EVEmptyViewLayoutKeySecondTitle];
        self.actionButtonTitle = [layout ev_stringObjectForKey:EVEmptyViewLayoutKeyButtonTitle];
    }
}

- (void)setIconImage:(UIImage *)iconImage {
    _iconImage = iconImage;
    
    self.iconImageView.image = _iconImage;
}

- (void)setMainTitle:(NSString *)mainTitle {
    _mainTitle = [mainTitle copy];
    
    self.mainTitleLabel.text = _mainTitle;
    [self refreshMainTitleLabelStyle];
    [self setNeedsLayout];
}

- (void)setSecondTitle:(NSString *)secondTitle {
    _secondTitle = [secondTitle copy];
    
    self.secondTitleLabel.text = _secondTitle;
    [self refreshMainTitleLabelStyle];
    [self setNeedsLayout];
}

- (void)setActionButtonTitle:(NSString *)actionButtonTitle {
    _actionButtonTitle = [actionButtonTitle copy];
    
    [self.actionButton setTitle:_actionButtonTitle forState:UIControlStateNormal];
    self.actionButton.hidden = isEmpty(actionButtonTitle);
}

- (void)refreshMainTitleLabelStyle {
    self.mainTitleLabel.font = isEmpty(self.secondTitle) ? [UIFont systemFontOfSize:15.0] : [UIFont systemFontOfSize:16.0];
    self.mainTitleLabel.textColor = isEmpty(self.secondTitle) ? [UIColor ev_minorTextColor] : [UIColor ev_majorTextColor];
}

- (IBAction)onEmptyViewTapped:(UITapGestureRecognizer *)sender {
    if (self.actionButton.hidden && self.actionBlock != nil) {
        self.actionBlock();
    }
}

- (IBAction)onActionButtonTouched:(id)sender {
    if (self.actionBlock != nil) {
        self.actionBlock();
    }
}

static NSDictionary *EmptyViewLayoutDictionary = nil;
+ (NSDictionary *)emptyViewLayouts {
    if (EmptyViewLayoutDictionary == nil) {
        EmptyViewLayoutDictionary =
        @{
          EVEmptyViewDefault:@{
                  EVEmptyViewLayoutKeyIcon:[UIImage imageNamed:@"empty_default"],
                  EVEmptyViewLayoutKeyMainTitle:@"暂无信息",
                  EVEmptyViewLayoutKeySecondTitle:@"",
                  EVEmptyViewLayoutKeyButtonTitle:@""
                  },
          EVEmptyViewError:@{
                  EVEmptyViewLayoutKeyIcon:[UIImage imageNamed:@"empty_default"],
                  EVEmptyViewLayoutKeyMainTitle:@"出错了！",
                  EVEmptyViewLayoutKeySecondTitle:@"",
                  EVEmptyViewLayoutKeyButtonTitle:@""
                  },
          EVEmptyViewNetwork:@{
                  EVEmptyViewLayoutKeyIcon:[UIImage imageNamed:@"empty_network"],
                  EVEmptyViewLayoutKeyMainTitle:@"网络不给力",
                  EVEmptyViewLayoutKeySecondTitle:@"建议检查网络后\r\n点击屏幕尝试重新连接",
                  EVEmptyViewLayoutKeyButtonTitle:@""
                  },
          EVEmptyViewOrder:@{
                  EVEmptyViewLayoutKeyIcon:[UIImage imageNamed:@"empty_order"],
                  EVEmptyViewLayoutKeyMainTitle:@"暂无充电记录",
                  EVEmptyViewLayoutKeySecondTitle:@"",
                  EVEmptyViewLayoutKeyButtonTitle:@""
                  },
          EVEmptyViewCoupon:@{
                  EVEmptyViewLayoutKeyIcon:[UIImage imageNamed:@"empty_coupon"],
                  EVEmptyViewLayoutKeyMainTitle:@"暂无优惠券",
                  EVEmptyViewLayoutKeySecondTitle:@"",
                  EVEmptyViewLayoutKeyButtonTitle:@""
                  },
          };
    }
    
    return EmptyViewLayoutDictionary;
}

@end

@implementation UIViewController (EVEmptyView)

- (EVEmptyView *)ev_showEmptyView {
    if (!self.ev_disableEmptyView) {
        self.ev_emptyView.frame = self.view.bounds;
        
        // 有NavigationBar时向下偏移
        if (self.navigationController != nil &&
            self.navigationController.topViewController == self &&
            self.parentViewController == self.navigationController &&
            (self.edgesForExtendedLayout & UIRectEdgeTop)) {
            
            const CGFloat statusBarAndNavigationBarHeight = 64.0;
            self.ev_emptyView.ev_top += statusBarAndNavigationBarHeight;
            self.ev_emptyView.ev_height -= statusBarAndNavigationBarHeight;
        }
        
        self.ev_emptyView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:self.ev_emptyView];
        
        return self.ev_emptyView;
    }
    return nil;
}

- (EVEmptyView *)ev_showEmptyViewForType:(NSString *)type {
    EVEmptyView *emptyView = [self ev_showEmptyView];
    emptyView.emptyViewType = type;
    
    return emptyView;
}

- (EVEmptyView *)ev_showEmptyViewForType:(NSString *)type title:(NSString *)title {
    EVEmptyView *emptyView = [self ev_showEmptyViewForType:type];
    emptyView.mainTitle = title;
    
    return emptyView;
}

- (EVEmptyView *)ev_showEmptyViewForError:(NSError *)error {
    BOOL isNetworkReachable = [ReachabilityHelper sharedInstance].currentReachabilityStatus != kNotReachable;
    if (![error isKindOfClass:[NSError class]]) {
        self.ev_emptyView.emptyViewType = EVEmptyViewError;
        self.ev_emptyView.secondTitle = @"未知错误";
    } else if (isNetworkReachable && error.code == kCFURLErrorCannotFindHost) {
        self.ev_emptyView.emptyViewType = EVEmptyViewError;
        self.ev_emptyView.secondTitle = @"未找到相关内容";
    } else if (!isNetworkReachable || [error isNetworkError]) {
        self.ev_emptyView.emptyViewType = EVEmptyViewNetwork;
    } else {
        self.ev_emptyView.emptyViewType = EVEmptyViewError;
        self.ev_emptyView.secondTitle = error.ev_errorMessage;
    }
    return [self ev_showEmptyView];
}

- (void)hideEmptyView {
    [self.ev_emptyView removeFromSuperview];
}

- (void)onEmptyViewResponded {
    // DO NOTHING
}

#pragma mark - Property
- (EVEmptyView *)ev_emptyView {
    EVEmptyView *_emptyView = objc_getAssociatedObject(self, _cmd);
    if (_emptyView == nil) {
        __weak __typeof(self) weakSelf = self;
        _emptyView = [EVEmptyView emptyViewWithIconImage:nil mainTitle:@"暂无信息" secondTitle:nil actionButtonTitle:nil actionBlock:^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf onEmptyViewResponded];
        }];
        
        objc_setAssociatedObject(self, @selector(ev_emptyView), _emptyView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    // 恢复标准的 actionBlock
    if (_emptyView.actionBlock == nil) {
        __weak __typeof(self) weakSelf = self;
        _emptyView.actionBlock = ^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf onEmptyViewResponded];
        };
    }
    
    return _emptyView;
}

- (BOOL)ev_disableEmptyView {
    NSNumber *_disableEmptyView = objc_getAssociatedObject(self, _cmd);
    return [_disableEmptyView boolValue];
}

- (void)ev_setDisableEmptyView:(BOOL)disableEmptyView {
    objc_setAssociatedObject(self, @selector(ev_disableEmptyView), @(disableEmptyView), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ev_emptyViewShown {
    return self.ev_emptyView.superview != nil;
}

- (void)ev_setEmptyViewShown:(BOOL)emptyViewShown {
    if (emptyViewShown) {
        [self ev_showEmptyView];
    } else {
        [self hideEmptyView];
    }
}

@end
